package cn.hairui.blog.controller;

import cn.hairui.blog.config.WebLog;
import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.Artical;
import cn.hairui.blog.model.Category;
import cn.hairui.blog.model.WebInfo;
import cn.hairui.blog.service.*;
import cn.hairui.blog.util.CommUtil;
import cn.hairui.blog.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author lihairui
 * @version V1.0
 * @date: 2019/3/5 22:42
 */
@Controller

public class ArticalController {

    @Autowired
    private WebInfoService webInfoService;
    @Autowired
    private ArticalService articalService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "artical")
    public String artical(HttpServletRequest request, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        int pageSize = 10;
        //关键字查询
        String keyword = null;
        String tag = null;
        try {
            keyword = request.getParameter("keyword");
        } catch (Exception e) {
            keyword = null;
        }
        try {
            tag = request.getParameter("tag");
        } catch (Exception e) {
            tag = null;
        }

        //分页信息 文章信息
        Integer pageNum = null;
        String pageNumStr = request.getParameter("pageIndex");
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Artical> articals = new ArrayList<>();
        if (keyword != null) {
            articals = articalService.findByKeyword(keyword);
        } else if (tag != null) {
            articals = articalService.findByTags(tag);
        }

        PageInfo<Artical> pageInfo = new PageInfo<Artical>(articals);
        List<Map> articalList = new ArrayList<Map>();
        //将对象转换为map 并在map中添加新的属性
        Iterator articalIterator = articals.iterator();
        while (articalIterator.hasNext()) {
            Map map = new HashMap();
            Artical artical = (Artical) articalIterator.next();
            map.put("id", artical.getId());
            map.put("title", artical.getTitle());
            map.put("summary", artical.getSummary());
            map.put("category", artical.getCategoryid());
            map.put("createdate", artical.getCreatedate());
            map.put("author", userService.findByUsername(artical.getAuthor()).getNickname());
            map.put("avatar", userService.findByUsername(artical.getAuthor()).getProphoto());
            int caId = artical.getCategoryid();
            String categoryidName = categoryService.find(caId).getCategoryName();
            map.put("categoryName", categoryidName);
            map.put("categoryId", caId);
            String tags = artical.getTags();
            List tagsList = CommUtil.tagStrToList(tags);
            map.put("tags", tagsList);
            articalList.add(map);
        }
        if (keyword != null) {
            model.addAttribute(PubConstant.flag, "1");//1表示关键字
            model.addAttribute("info", keyword);
        }
        if (tag != null) {
            model.addAttribute(PubConstant.flag, "2");//2表示标签
            model.addAttribute("info", tag);
        }

        model.addAttribute("articals", articalList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageIndex", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "artical";
    }

    @RequestMapping(value = "view")
    public String articalView(int id, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        Artical artical = articalService.find(id);
        String articalType = artical.getType();
        if (PubConstant.DIC_TYPE_0.equals(articalType)) {
            model.addAttribute("articalTypeCn", "原创");
        } else {
            model.addAttribute("articalTypeCn", "转载");
        }
        int categoryId = artical.getCategoryid();
        Category category = categoryService.find(categoryId);
        String categoryCn = category.getCategoryName();
        if (categoryCn == null || "".equals(categoryCn)) {
            model.addAttribute("categoryCn", "其他");
        } else {
            model.addAttribute("categoryCn", categoryCn);
        }
        model.addAttribute("authorCn", userService.findByUsername(artical.getAuthor()).getNickname());
        model.addAttribute("artical", artical);
        Artical articalLast = articalService.findLast(id);
        Artical articalNext = articalService.findNext(id);
        model.addAttribute("articalLast", articalLast);
        model.addAttribute("articalNext", articalNext);

        String tags = artical.getTags();
        List tagsList = CommUtil.tagStrToList(tags);
        model.addAttribute("tags", tagsList);

        return "view";
    }

    @RequestMapping(value = "/category")
    @WebLog(description = "查看文章分类")
    public String showCategoryid(HttpServletRequest request, Model model) {

        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        int pageSize = 10;
        Integer categoryId = 0;
        String idStr = request.getParameter("id");
        if (idStr != null && !"null".equals(idStr)) {
            try {
                categoryId = Integer.parseInt(idStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (categoryId != 0) {
                Category category = categoryService.find(categoryId);
                model.addAttribute("categoryName", "# " + category.getCategoryName());
            } else {
                model.addAttribute("categoryName", "# 全部分类");
            }
        } else {
            model.addAttribute("categoryName", "# 全部分类");
        }
        //分类信息

        List<Map> categoryList = categoryService.findCountList();
        Iterator categoryidIterator = categoryList.iterator();
        List<Map> categoryInfosList = new ArrayList<>();
        while (categoryidIterator.hasNext()) {
            Map map = new HashMap();
            Map articalCategoryid = (Map) categoryidIterator.next();
            map.put("categoryName", articalCategoryid.get("categoryName"));
            map.put("categoryNum", articalCategoryid.get("categoryNum"));
            map.put("categoryId", articalCategoryid.get("categoryId"));
            if (Integer.parseInt(articalCategoryid.get("categoryId").toString()) == categoryId) {
                map.put("current", "Y");
            } else {
                map.put("current", "N");
            }
            categoryInfosList.add(map);
        }
        model.addAttribute("categoryInfos", categoryInfosList);


        //分页信息 文章信息
        Integer pageNum = null;
        String pageNumStr = request.getParameter("pageIndex");
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Artical> articals = new ArrayList<>();
        if (categoryId == 0) {
            //查詢所有
            articals = articalService.list();
        } else {
            articals = articalService.findByCategoryId(categoryId);
        }
        PageInfo<Artical> pageInfo = new PageInfo<Artical>(articals);
        List<Map> articalList = new ArrayList<Map>();
        //将对象转换为map 并在map中添加新的属性
        Iterator articalIterator = articals.iterator();
        while (articalIterator.hasNext()) {
            Map map = new HashMap();
            Artical artical = (Artical) articalIterator.next();
            map.put("id", artical.getId());
            map.put("title", artical.getTitle());
            map.put("summary", artical.getSummary());
            map.put("category", artical.getCategoryid());
            map.put("createdate", artical.getCreatedate());
            map.put("author", userService.findByUsername(artical.getAuthor()).getNickname());
            map.put("avatar", userService.findByUsername(artical.getAuthor()).getProphoto());
            int caId = artical.getCategoryid();
            String categoryidName = categoryService.find(caId).getCategoryName();
            map.put("categoryName", categoryidName);
            map.put("categoryId", caId);
            String tags = artical.getTags();
            List tagsList = CommUtil.tagStrToList(tags);
            map.put("tags", tagsList);
            articalList.add(map);
        }
        model.addAttribute("articals", articalList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageIndex", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "category";
    }


    @RequestMapping(value = "/archive")
    @WebLog(description = "查看文章归档")
    public String showArchives(HttpServletRequest request, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);
        int pageSize = 10;
        List<Map> archiveList = articalService.listArchive();
        String dateStr = request.getParameter("date");

        Iterator archivesIterator = archiveList.iterator();
        List<Map> archivesnfosList = new ArrayList<>();
        while (archivesIterator.hasNext()) {
            Map map = new HashMap();
            Map archives = (Map) archivesIterator.next();
            String createdate = (String) archives.get("CREATEDATE");
            Long num = (Long) archives.get("NUM");

            map.put("createdate", createdate);
            map.put("createdateCn", createdate.replaceAll("-", "年") + "月");
            map.put("num", num);
            if (dateStr != null && dateStr.replace("-", "").equals(createdate.replace("-", ""))) {
                map.put("current", "Y");
            } else {
                map.put("current", "N");
            }
            archivesnfosList.add(map);
        }

        model.addAttribute("archives", archivesnfosList);

        Integer pageNum = null;
        String pageNumStr = request.getParameter("pageIndex");
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }

        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Artical> articals = new ArrayList<>();
        if (dateStr == null || "null".equals(dateStr)) {
            //查詢所有
            articals = articalService.list();
            model.addAttribute("date", "null");
        } else {
            articals = articalService.findByCreateDateYm(DateUtil.convertDate(dateStr));
            model.addAttribute("date", dateStr.replaceAll("-", ""));
        }

        PageInfo<Artical> pageInfo = new PageInfo<Artical>(articals);
        List<Map> articalList = new ArrayList<Map>();
        Iterator articalIterator = articals.iterator();
        while (articalIterator.hasNext()) {
            Map map = new HashMap();
            Artical artical = (Artical) articalIterator.next();
            map.put("id", artical.getId());
            map.put("title", artical.getTitle());
            map.put("summary", artical.getSummary());
            map.put("category", artical.getCategoryid());
            map.put("createdate", artical.getCreatedate());
            map.put("author", userService.findByUsername(artical.getAuthor()).getNickname());
            map.put("avatar", userService.findByUsername(artical.getAuthor()).getProphoto());
            int caId = artical.getCategoryid();
            String categoryidName = categoryService.find(caId).getCategoryName();
            map.put("categoryName", categoryidName);
            map.put("categoryId", caId);
            String tags = artical.getTags();
            List tagsList = CommUtil.tagStrToList(tags);
            map.put("tags", tagsList);
            articalList.add(map);
        }
        model.addAttribute("articals", articalList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageIndex", pageNum);
        model.addAttribute("pageSize", pageSize);

        /*if (dateStr == null || "null".equals(dateStr)) {
            model.addAttribute("archiveStatistic", "您一共发布了" + pageInfo.getTotal() + "篇文章");
        } else {
            model.addAttribute("archiveStatistic", "您在" + dateStr.replaceAll("-", "年") + "月，一共发布了" + pageInfo.getTotal() + "篇文章");
        }*/
        return "archive";
    }

    @RequestMapping(value = "/topic")
    @WebLog(description = "查看文章专题")
    public String topic(HttpServletRequest request, Model model) {

        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        int pageSize = 10;
        Integer topicId = 0;
        String idStr = request.getParameter("id");
        if (idStr != null && !"null".equals(idStr)) {
            try {
                topicId = Integer.parseInt(idStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*if (topicId != 0) {
                Topic category = articalService.findByTopicId(topicId);
                model.addAttribute("categoryName", "# " + category.getCategoryName());
            } else {
                model.addAttribute("categoryName", "# 全部分类");
            }*/
        } else {
            /*model.addAttribute("categoryName", "# 全部分类");*/
        }
        //分类信息

        List<Map> topicList = topicService.findCountList();
        Iterator iterator = topicList.iterator();
        List<Map> topicInfosList = new ArrayList<>();
        while (iterator.hasNext()) {
            Map map = new HashMap();
            Map topic = (Map) iterator.next();
            map.put("topicName", topic.get("topicName"));
            map.put("topicNum", topic.get("topicNum"));
            map.put("topicId", topic.get("topicId"));
            if (Integer.parseInt(topic.get("topicId").toString()) == topicId) {
                map.put("current", "Y");
            } else {
                map.put("current", "N");
            }
            topicInfosList.add(map);
        }
        model.addAttribute("topicInfos", topicInfosList);


        //分页信息 文章信息
        Integer pageNum = null;
        String pageNumStr = request.getParameter("pageIndex");
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Artical> articals = new ArrayList<>();
        if (topicId == 0) {
            //查詢所有
            articals = articalService.list();
        } else {
            articals = articalService.findByTopicId(topicId);
        }
        PageInfo<Artical> pageInfo = new PageInfo<Artical>(articals);
        List<Map> articalList = new ArrayList<Map>();
        //将对象转换为map 并在map中添加新的属性
        Iterator articalIterator = articals.iterator();
        while (articalIterator.hasNext()) {
            Map map = new HashMap();
            Artical artical = (Artical) articalIterator.next();
            map.put("id", artical.getId());
            map.put("title", artical.getTitle());
            map.put("summary", artical.getSummary());
            map.put("category", artical.getCategoryid());
            map.put("createdate", artical.getCreatedate());
            map.put("author", userService.findByUsername(artical.getAuthor()).getNickname());
            map.put("avatar", userService.findByUsername(artical.getAuthor()).getProphoto());
            int caId = artical.getCategoryid();
            String categoryidName = categoryService.find(caId).getCategoryName();
            map.put("categoryName", categoryidName);
            map.put("categoryId", caId);
            String tags = artical.getTags();
            List tagsList = CommUtil.tagStrToList(tags);
            map.put("tags", tagsList);
            articalList.add(map);
        }
        model.addAttribute("articals", articalList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageIndex", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "topic";
    }


    @RequestMapping(value = "/tags")
    @WebLog(description = "查看文章标签")
    public String tags(HttpServletRequest request, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);



        /*List<String> result = new LinkedList<>();
        List<String> tagsList = articalService.findtags();
        for (String tag : tagsList
        ) {
            String[] args = tag.split("/");
            for (String arg : args
            ) {

                if (!result.contains(arg.replaceAll("#", ""))) {
                    result.add(arg.replaceAll("#", ""));
                }
            }
        }
       */

        List<String> tagsList = articalService.findtags();
        List<Map> tags = new ArrayList<>();
        Iterator it = tagsList.iterator();

        while (it.hasNext()) {
            Map map = new HashMap();
            String tagName = it.next().toString();
            int count = articalService.findCountByTagName(tagName);
            map.put("name", tagName);
            map.put("num", count);
            map.put("color", CommUtil.createRandomColor());
            tags.add(map);
        }
        model.addAttribute("tags", tags);
        return "tags";
    }

}
